import { createRouter, createWebHistory } from 'vue-router'

const routes = [
  {
    path: '/',
    name: 'Login',
    component: () => import('../views/Login.vue')
  },
  {
    path:'/register',
    name:'Register',
    component: () => import('../views/Register.vue')
  },
  {
    path: '/blog',
    name: 'Blog',
    component: () => import('../views/Blog.vue'),
    meta: { requireAuth: true }
  },
  {
    path: '/personal-home',
    name: 'PersonalHome',
    component: () => import('../views/PersonalHome.vue'),
    meta: { requireAuth: true }
  },
  {
    path: '/myhome',
    name: 'Myhome',
    component: () => import('../views/Myhome.vue'),
    meta: { requireAuth: true }
  },
  {
    path: '/journey',
    name: 'Journey',
    component: () => import('../components/Journey.vue')
  },
  {
    path: '/technical-blog',
    name: 'TechnicalBlog',
    component: () => import('../components/TechnicalBlog.vue'),
    meta: { requireAuth: true }
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: () => import('../views/NotFound.vue')
  }
]

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes,
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    } else {
      return { top: 0 }
    }
  }
})

router.beforeEach(async (to, from, next) => {
  const requiresAuth = to.matched.some(record => record.meta.requireAuth)
  const token = localStorage.getItem('jwtToken')

  if (requiresAuth && !token) {
    next('/')
  } else {
    next()
  }
})

export default router